<template>
  <div class="page rolePage">
    <div class="p20">
      <el-row>
        <el-col :span="8">
          <div class="c-aside">
            <div class="c-head">
              <el-button
                type="primary"
                size="mini"
                class="btn"
                @click="rTriggerAddRole"
                v-hasAuth:system_authorityCreateRole
                >新增角色</el-button
              >
            </div>
            <div class="c-body">
              <!-- <el-tree
            :data="orgAjax.offspringnTreeData"
            :props="roleTreeCp.config.defaultProps"
            accordion
            :expand-on-click-node="false"
            :highlight-current="true">
            <div class="custom-tree-node" slot-scope="{ node}">
              <el-dropdown trigger="click" split-button @command="rRoleTreeItemClick">
                  {{ node.label + '111' }}
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-edit">修改</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-delete">删除</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            </div>
            </el-tree> -->
              <div class="p20">
                <el-table
                  :data="pageAjax.data"
                  style="width: 100%"
                  :show-header="false"
                  highlight-current-row
                  ref="roleTreeCpRef"
                  @current-change="rChangeRole"
                >
                  <el-table-column>
                    <template slot-scope="scope">
                      {{ scope.row.roleName }}
                      <el-dropdown
                        trigger="click"
                        class="fr"
                        @command="rRoleTreeItemClick"
                        v-hasAuth:system_authorityEditRole-system_authorityDeleteRole
                      >
                        <i class="el-icon-more"></i>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item
                            icon="el-icon-edit"
                            :command="{ data: scope.row, type: 'edit' }"
                            v-hasAuth:system_authorityEditRole
                            >修改</el-dropdown-item
                          >
                          <el-dropdown-item
                            icon="el-icon-delete"
                            :command="{ data: scope.row, type: 'delete' }"
                            v-hasAuth:system_authorityDeleteRole
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </el-dropdown>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="c-section">
            <el-tabs
              v-model="functionTabCp.data.current"
              v-if="roleTreeCp.currentRow"
            >
              <el-tab-pane label="功能" name="function">
                <div class="c-head clearfix">
                  设置角色对应的功能操作权限
                  <el-button
                    type="primary"
                    size="mini"
                    class="btn fr"
                    @click="rSaveRoleFunction"
                    v-hasAuth:system_authorityEditRole
                    >保存</el-button
                  >
                  <div class="fr mr20">
                    <el-checkbox
                      v-model="alone.checkAllFn"
                      @change="rCheckAllFn"
                      >全选</el-checkbox
                    >
                  </div>
                </div>
                <div class="c-body">
                  <el-tree
                    show-checkbox
                    node-key="id"
                    ref="fnTreeCpRef"
                    :data="functionSupAjax.data"
                    :default-checked-keys="alone.checkedFn"
                    :props="fnTreeCp.config.defaultProps"
                    :check-strictly="fnTreeCp.config.checkStrictly"
                  >
                  </el-tree>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 新增角色 -->
    <el-drawer
      :title="addRoleCp.config.title"
      :visible.sync="addRoleCp.config.visible"
      :direction="addRoleCp.config.direction"
      :size="addRoleCp.config.size"
    >
      <el-row class="f-addRoleDrawer">
        <el-col :span="12" :offset="6">
          <el-form ref="status" label-width="120px">
            <el-form-item label="角色中文名称">
              <el-input v-model="addRoleAjax.data.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色英文名称">
              <el-input v-model="addRoleAjax.data.roleNameEn"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="addRoleAjax.data.remarks"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="rSubmitAddRoleForm"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { getOffspringnTree } from "@/assets/js/util.js";
import {
  deleteRole,
  addRole,
  getRoleFunction,
  addRoleFunction
} from "@/api/authority.js";

// let getRoleFunctionTt = throttle(getRoleFunction, 1500);
import _ from "lodash";

export default {
  name: "system_authorityRoleList",
  data: () => ({
    // 获取角色数据
    pageAjax: {
      btnDisabled: false,
      btnLoading: false,
      loading: false,
      lock: false,
      paging: {
        pages: 1, // 总页数
        current: 0, // 当前页
        total: 1, // 总数量
        pageSize: 10 // 每页数量
      },
      data: []
    },
    // 全部功能节点
    functionSupAjax: {
      data: []
    },
    // 增加角色
    addRoleAjax: {
      loading: false,
      data: {
        roleName: "",
        roleNameEn: "",
        remarks: ""
      }
    },
    orgAjax: {
      data: [],
      orginData: [], // 默认包含父级节点
      offspringnTreeData: [] // 用于下拉框
    },
    alone: {
      checkAllFn: false,
      checkedFn: [],
      searchForm: {
        loading: false,
        data: {
          name: "",
          parentId: 0
        }
      }
    },
    // 角色列表组件配置
    roleTreeCp: {
      config: {
        defaultProps: {
          children: "children",
          label: "name"
        },
        checkStrictly: true
      },
      currentRow: null // 当前选中的行
    },
    // 功能列表组件配置
    fnTreeCp: {
      config: {
        defaultProps: {
          children: "children",
          label: "name"
        },
        visible: false,
        checkStrictly: false
      }
    },
    // 功能列表tab配置
    functionTabCp: {
      config: {},
      data: {
        current: "function"
      }
    },
    // 增加功能组件配置
    addRoleCp: {
      config: {
        title: "",
        visible: false,
        direction: "ttb",
        size: "70%"
      }
    },
    orgCascaderCp: {
      config: {
        props: {
          value: "id",
          label: "name",
          checkStrictly: true
        }
      }
    }
  }),
  computed: {
    ...mapGetters([
      // 'functionListOffspringn',
      "functionListOffspringnTreeData"
    ])
  },
  watch: {
    "pageAjax.data"() {
      this.setCurrentRow();
    }
  },
  created() {
    let _that = this;
    // 获取角色列表数据
    _that.getPageData();
    // 获取所有功能列表数据
    _that.getFunctionSupData();
  },
  methods: {
    // 存储当前选中的角色行
    rChangeRole(v) {
      let _that = this;
      // _that.$refs.fnTreeCpRef.setCheckedNodes([]);
      // _that.alone.checkedFn = false;
      if (v) {
        _that.roleTreeCp.currentRow = v;
        _that.getRoleFunction();
      }
    },
    // 设置当前选中的角色行
    setCurrentRow() {
      let _that = this;
      let pageAjaxData = _that.pageAjax.data;
      let currentRow = this.roleTreeCp.currentRow;
      let index;
      if (!currentRow) {
        return;
      }
      for (var i = pageAjaxData.length; i--; ) {
        if (currentRow.id == pageAjaxData[i].id) {
          index = i;
        }
      }
      this.$refs.roleTreeCpRef.setCurrentRow(_that.pageAjax.data[index]);
    },
    // 触发添加角色
    rTriggerAddRole() {
      let _that = this;
      _that.addRoleAjax.data = {
        roleName: "",
        roleNameEn: "",
        remarks: ""
      };
      _that.addRoleCp.config.visible = true;
    },
    // 添加角色提交
    rSubmitAddRoleForm() {
      let _that = this;
      let addRoleAjax = _that.addRoleAjax;
      let addRoleAjaxData = addRoleAjax.data;

      if (addRoleAjax.loading) {
        return;
      }
      if (!addRoleAjaxData.roleName || !addRoleAjaxData.roleNameEn) {
        _that.$message.error("角色中文名称和英文名不能为空");
        return;
      }
      _that.addRoleAjax.loading = true;

      addRole(addRoleAjaxData)
        .then(resp => {
          let respData = resp.data;
          if (respData.code === _that.STATUS.success[0]) {
            _that.addRoleCp.config.visible = false;
            _that.getPageData();
            _that.$message.success({
              message: respData.msg || "添加失败",
              onClose() {}
            });
          } else {
            _that.$message.error(respData.msg || "添加失败");
          }
        })
        .finally(() => {
          _that.addRoleAjax.loading = false;
        });
    },
    // 修改和删除角色
    rRoleTreeItemClick(objParams) {
      let _that = this;
      let type = objParams.type;
      let rowData = objParams.data;
      let currentRow = _that.roleTreeCp.currentRow;

      if (type == "edit") {
        _that.addRoleAjax.data = rowData;
        _that.addRoleCp.config.visible = true;
      } else if (type == "delete") {
        _that
          .$confirm("你确定要删除此数据?", "删除提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            deleteRole({ id: rowData.id }).then(resp => {
              let respData = resp.data || {};

              if (respData.code === _that.STATUS.success[0]) {
                _that.$message.success(respData.msg || "删除成功");
                if (currentRow && currentRow.id == rowData.id) {
                  _that.roleTreeCp.currentRow = null;
                }
                _that.getPageData();
              } else {
                _that.$message.error(respData.msg || "删除失败");
              }
            });
          })
          .catch(() => {});
      }
    },
    // 获取角色的功能
    getRoleFunction: (() => {
      return _.debounce(function() {
        let _that = this;
        let id = _that.roleTreeCp.currentRow.id;
        getRoleFunction({ params: { id: id } }).then(resp => {
          let respData = resp.data;
          if (respData.code === _that.STATUS.success[0]) {
            let arr = respData.data.funcIds || [];
            _that.$refs.fnTreeCpRef.setCheckedKeys(arr);
            _that.alone.checkedFn = arr;

            if (arr.length < _that.$store.state.functionList.length) {
              _that.alone.checkAllFn = false;
            } else {
              _that.alone.checkAllFn = true;
            }
          }
        });
      }, 400);
    })(),
    // 功能全选
    rCheckAllFn(val) {
      let _that = this;
      let data = _that.functionSupAjax.data;
      let arr = [];
      if (val) {
        for (var i = data.length; i--; ) {
          arr.push(data[i].id);
        }
      }
      _that.$refs.fnTreeCpRef.setCheckedNodes(arr);
      _that.alone.checkedFn = arr;
    },
    // 保存对应角色的功能
    rSaveRoleFunction() {
      let _that = this;
      let currentRow = _that.roleTreeCp.currentRow;
      if (!currentRow) {
        return;
      }
      let loadingHand = _that.$loading();

      let checkedKeys = _that.$refs.fnTreeCpRef.getCheckedKeys();
      // let arrCheckedKeys = _that.$refs.fnTreeCpRef.getCheckedKeys();
      // let arrHalfCheckedKeys = _that.$refs.fnTreeCpRef.getHalfCheckedKeys();
      // checkedKeys = arrCheckedKeys.concat(arrHalfCheckedKeys);

      addRoleFunction({ roleId: currentRow.id, funcIds: checkedKeys })
        .then(resp => {
          let respData = resp.data;
          if (respData.code === _that.STATUS.success[0]) {
            _that.$message.success({
              message: respData.msg || "添加失败",
              onClose() {}
            });
          } else {
            _that.$message.error(respData.msg || "添加失败");
          }
        })
        .finally(() => {
          loadingHand.close();
        });
    },
    getPageData() {
      let _that = this;
      _that.$store
        .dispatch("getRoleList", { vue: _that, latest: true })
        .then(() => {
          _that.pageAjax.data = _that.$store.state.roleList;
        });
    },
    getFunctionSupData() {
      let _that = this;
      _that.$store.dispatch("getFunctionList", { vue: _that }).then(() => {
        let arr = _.cloneDeep(_that.$store.state.functionList) || [];
        _that.functionSupAjax.orginData = arr;

        _that.functionSupAjax.data = getOffspringnTree(_.cloneDeep(arr), 0);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.page {
  .c-aside {
    padding-top: 5px;
    border-right: 1px solid #f3f3f3;
    border-top: 1px solid #f3f3f3;
  }
  .c-section {
    padding: 20px;
    border-top: 1px solid #f3f3f3;
    .c-head {
      line-height: 30px;
    }
  }
}
</style>
<style lang="scss">
.rolePage {
  .el-tree-node__content {
    height: 40px;
  }
  .custom-tree-node {
    .el-tree-node__content {
      &:hover {
        .el-button {
          background-color: #f5f7fa;
        }
      }
    }
    .el-button-group {
      .el-button {
        border: none;
        background-color: transparent;
        &:hover {
          background-color: #f5f7fa;
        }
      }
      .el-button:last-child {
        &:before {
          display: none;
        }
      }
    }
  }
}
</style>
